package com.sgb.kjwl.viewmodel.transport;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.MyCarInfoEntity;
import com.sgb.kjwl.model.entity.self.EnergyTypeEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

public class SelfCarInfoViewModel extends BaseViewModel {
    //页面接口
    public MutableLiveData<MyCarInfoEntity> ldCar = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarLen = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarFunc = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldColor = new MutableLiveData<>();
    public MutableLiveData<String> ldImage = new MutableLiveData<>();
    public MutableLiveData<List<EnergyTypeEntity>> ldEnergy = new MutableLiveData<>();

    public SelfCarInfoViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    /**
     * 提交数据
     */
    public MyCarInfoEntity submitData() {
        if (ldCar.getValue() == null) {
            ldCar.setValue(new MyCarInfoEntity());
        }
        return ldCar.getValue();
    }

    /**
     * 获取车辆详情
     */
    public void getCarDetail(Context context, long no) {
        DialogHelper.showProgressDialog(context, "加载中");
        NewAPIManager.getInstance().getLogisticsAPI().getJingDriverDetail(no)
                .enqueue(new ICallBack<BaseEntity<MyCarInfoEntity>>() {
                    @Override
                    public void onSuccess(BaseEntity<MyCarInfoEntity> data) {
                        if (data.getData() == null) {
                            MToast.showToast(getApplication(), "暂无数据");
                        } else {
                            ldCar.postValue(data.getData());
                        }
                    }
                });
    }

    /**
     * 获取车型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getAllCarType()
                .enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
                    @Override
                    public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                        ldCarType.postValue(data.getData());
                    }
                });
    }

    /**
     * 获取车长
     */
    public void getCarLengthList(String no) {
        //根据车型获取
        NewAPIManager.getInstance().getLogisticsAPI().getCarLenByType(no)
                .enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
                    @Override
                    public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                        ldCarLen.postValue(data.getData());
                    }
                });
    }

    /**
     * 获取车牌颜色
     */
    public void getColorList() {
        List<GoodsInfoTypeEntity3> colors = new ArrayList<>();
        colors.add(new GoodsInfoTypeEntity3("2", "黄色"));
        colors.add(new GoodsInfoTypeEntity3("1", "蓝色"));
        colors.add(new GoodsInfoTypeEntity3("9", "绿色"));
        ldColor.postValue(colors);
    }

    /**
     * 获取车辆功能
     */
    public void getCarFunctionList() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarFunction()
                .enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
                    @Override
                    public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                        ldCarFunc.postValue(data.getData());
                    }
                });
    }

    /**
     * 获取能源类型
     */
    public void getEnergyList() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarEnergyType()
                .enqueue(new ICallBack<BaseEntity<List<EnergyTypeEntity>>>() {
                    @Override
                    public void onSuccess(BaseEntity<List<EnergyTypeEntity>> data) {
                        ldEnergy.postValue(data.getData());
                    }
                });
    }

    /**
     * 上传图片
     */
    public void uploadFile(Context context, File file) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file\";filename=\"image.jpg", requestBody);
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (!data.isSuccess()) {
                    onFail();
                    return;
                }
                ldImage.postValue(data.getData().toString());
            }

            @Override
            public void onFail() {
                super.onFail();
                ldImage.postValue("");
            }
        });
    }

    /**
     * 保存数据
     */
    public void save(Context context, View view, MyCarInfoEntity entity) {
        if (entity == null) return;
        if (TextUtils.isEmpty(entity.getCarTypeNo())) {
            MToast.showToast(context, "请选择车型");
            return;
        }
        if (TextUtils.isEmpty(entity.getCarLenNo())) {
            MToast.showToast(context, "请选择车长");
            return;
        }
        if (TextUtils.isEmpty(entity.getWeight())) {
            MToast.showToast(context, "请输入车辆额定载重");
            return;
        }
        if (TextUtils.isEmpty(entity.getLicensePlateColor())) {
            MToast.showToast(context, "请选择车辆颜色");
            return;
        }
        if (entity.getLatitude() == 0 || entity.getLongitude() == 0) {
            MToast.showToast(context, "请选择车辆所在地");
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if (entity.getId() != 0) {
            map.put("id", entity.getId());
        }
        map.put("carTypeNo", entity.getCarTypeNo());
        map.put("carLenNo", entity.getCarLenNo());
        map.put("weight", entity.getWeight());
        map.put("licensePlateColor", entity.getLicensePlateColor());
        if (entity.getAcquireTime() != null && entity.getAcquireTime() != 0) {
            map.put("acquireTime", entity.getAcquireTime());
        }
        if (!TextUtils.isEmpty(entity.getTransportCertificateMain())) {
            map.put("transportCertificateMain", entity.getTransportCertificateMain());
        }
        if (!TextUtils.isEmpty(entity.getTransportCertificateNum())) {
            map.put("transportCertificateNum", entity.getTransportCertificateNum());
        }
        if (!TextUtils.isEmpty(entity.getHeightHurdle())) {
            map.put("heightHurdle", entity.getHeightHurdle());
        }
        if (entity.getIsDump() != null) {
            map.put("isDump", entity.getIsDump());
        }
        map.put("functionNos", entity.getFunctionNo());
        //定位信息
        map.put("provinceNo", entity.getProvinceNo());
        map.put("provinceName", entity.getProvinceName());
        map.put("cityNo", entity.getCityNo());
        map.put("cityName", entity.getCityName());
        map.put("districtNo", entity.getDistrictNo());
        map.put("districtName", entity.getDistrictName());
        map.put("detailAddress", entity.getDetailAddress());
        map.put("longitude", entity.getLongitude());
        map.put("latitude", entity.getLatitude());
        //车辆上户地
        map.put("carProvinceName", entity.getCarProvinceName());
        map.put("carProvinceNo", entity.getCarProvinceNo());
        map.put("carCityName", entity.getCarCityName());
        map.put("carCityNo", entity.getCarCityNo());
        map.put("carDistrictName", entity.getCarDistrictName());
        map.put("carDistrictNo", entity.getCarDistrictNo());
        //保险时间
        map.put("insuranceTime", entity.getInsuranceTime());
        //年检时间
        map.put("annualInspectionTime", entity.getAnnualInspectionTime());
        //上次保养时间
        map.put("upMaintainTime", entity.getUpMaintainTime());
        //当前去向
        map.put("intentionProvinceNo", entity.getIntentionProvinceNo());
        map.put("intentionProvinceName", entity.getIntentionProvinceName());
        map.put("intentionCityNo", entity.getIntentionCityNo());
        map.put("intentionCityName", entity.getIntentionCityName());
        //车辆年限
        if (entity.getCarYears() == null) {
            map.put("carYears", 0);
        } else {
            map.put("carYears", entity.getCarYears());
        }

        if (!TextUtils.isEmpty(entity.getImageIssuingAuthority())) {
            map.put("imageIssuingAuthority", entity.getImageIssuingAuthority());
        }
        if (!TextUtils.isEmpty(entity.getImageSourceCode())) {
            map.put("imageSourceCode", entity.getImageSourceCode());
        }
        view.setEnabled(false);
        DialogHelper.showProgressDialog(context, "请稍等...");
        NewAPIManager.getInstance().getLogisticsAPI().authCar(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                view.setEnabled(true);
                if (data.isSuccess()) {
                    MToast.showToast(context, "保存成功");
                    EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_CARINFO_COMMIT));
                    ((Activity) context).finish();
                } else {
                    MToast.showToast(context, "操作失败");
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                super.onFailure(call, t);
                view.setEnabled(true);
                MToast.showToast(context, "操作失败");
            }
        });
    }
}
